﻿using System;
using System.Configuration;
using System.Web;
using HiTeachers.Utilities;

namespace HiTeachers.Web.SchedulerJobs
{
    public class HiTeachersHttpModule : IHttpModule
    {
        private static readonly object Sync = new object();

        public void Init(HttpApplication context)
        {
            context.Disposed += new EventHandler(ContextDisposed);

            System.Threading.Thread schedulerThread = HiTeachersApplication.SchedulerThread;

            if (schedulerThread != null) return;

            lock (Sync)
            {
                if (schedulerThread != null) return;
                Logger.Info("Creating new scheduler thread");

                Scheduler scheduler = new Scheduler(
                    HttpContext.Current.Request.Url.AbsoluteUri,
                    int.Parse(ConfigurationManager.AppSettings["emailThreadSleepInterval"]),
                    new ISchedulerJob[] { new EmailJob() });

                schedulerThread = new System.Threading.Thread(new System.Threading.ThreadStart(scheduler.Start));
                schedulerThread.Start();

                HiTeachersApplication.SchedulerThread = schedulerThread;
            }
        }

        static void ContextDisposed(object sender, EventArgs e)
        {
            if (HttpContext.Current == null) return;

            System.Threading.Thread schedulerThread = HiTeachersApplication.SchedulerThread;

            //  Code that runs on application shutdown
            if (schedulerThread == null) return;

            Logger.Info("Disposing scheduler thread");

            schedulerThread.Abort();
        }

        public void Dispose()
        {

        }
    }
}
